<template>
  <div class="mt-1">
    <van-form>
      <van-field
        is-link
        label="关联单号"
        placeholder="点击此处获取关联单号"
        :value="orderNum"
        @click="getOrderNum"
        readonly
      ></van-field>
      <van-field
        label="收货工厂"
        :value="orderMill"
        placeholder="点击关联单号获取"
        readonly
      >
      </van-field>
      <van-field
        label="CNN"
        :value="orderStorage"
        placeholder="点击关联单号获取"
        readonly
      >
      </van-field>
      <!-- 拍码 -->
      <van-field
        v-model="code"
        placeholder="请扫描拍码"
        clearable
        label="拍码"
        ref="code"
        @focus="focus"
      />
      <ag-grid-vue
        style="width: 100%; height: 300px"
        class="ag-theme-alpine mt-1"
        :columnDefs="columnDefs"
        :defaultColDef="defaultColDef"
        :gridOptions="gridOptions"
        rowSelection="single"
        :rowData="rowData"
      >
      </ag-grid-vue>
      <van-row type="flex" gutter="30" justify="center">
        <van-col span="9">
          <van-button type="danger" class="mt-1" @click="onRemoveSelected" block
            >删除</van-button
          ></van-col
        >
        <!-- <van-col span="7"
          ><van-button type="info" class="mt-1" @click="updateNum" block
            >修改数量</van-button
          ></van-col
        > -->
        <van-col span="9"
          ><van-button type="info" class="mt-1" @click="onSubmit" block
            >提交</van-button
          ></van-col
        >
      </van-row>
      <!-- 明细组件 -->
      <van-popup
        v-model="ShowStatue"
        position="bottom"
        style="height: 100%"
        class="bg-default"
      >
        <ShowDataZS :ShowDataA="ShowData" @get-val="Suretwo" />
      </van-popup>
      <com-dialog
        :statu="show"
        :DX="DX"
        @confirmButton="confirmButton"
        @cancelButton="cancelButton"
      ></com-dialog>

      <van-popup
        v-model="orderNumBerVisible"
        position="bottom"
        style="height: 100%"
        class="bg-default"
      >
        <OrderNumBer @closetwo="closetwo" @close="close" @get_date="get_date" />
      </van-popup>
    </van-form>

    <!-- 修改数量的弹窗提示 -->
    <van-dialog
      v-model="ifShowUpdateNum"
      title="请输入要修改的数量"
      show-cancel-button
      @confirm="SureUpdate"
    >
      <van-field
        v-model="needUpdateNum"
        type="number"
        placeholder="请输入数量"
      />
    </van-dialog>
    <!-- 展示数量不符的物料名称 -->
    <van-dialog v-model="ifShowNoFit" title="数量不符"> </van-dialog>
  </div>
</template>

<script>
import { AgGridVue } from "ag-grid-vue";
import { PostSubmitA, PostOrder } from "../../assets/api/post";
import ComDialog from "../../layout/ComDialog.vue";
import { toast, parseQRCode } from "../../untils/commion";
import ShowDataZS from "../../components/ShowData.vue";
import { AgGrid } from "../../minx/AgGrid";
import OrderNumBer from "./OrderNumber.vue";

export default {
  name: "Warehousing",
  components: { AgGridVue, ComDialog, ShowDataZS, OrderNumBer },
  mixins: [AgGrid],
  data() {
    return {
      ifShowNoFit: false,
      orderNumBerVisible: false,
      titles: new Map().set(1, "STO收货"),
      type: null,
      show: false,
      zt: true,
      location: "",
      ShowStatue: false,
      needUpdateNum: "", //修改后存放数据
      ifShowUpdateNum: false, //修改数量弹窗
      selectDate: [], //选中的行数据
      code: "",
      orderNum: "",
      orderStorage: "",
      orderMill: "",
      columnDefs: [
        { headerName: "物料", field: "materialCode", flex: 1.5 },
        { headerName: "拍号", field: "palletNo", flex: 2 },
        { headerName: "数量", field: "quantity", flex: 1.5 },
      ],
      rowData: [],
      plantcode: "",
      cnn: "",
      sure: "",
      sum: 0,
      otherData: [],
      info: [],
      DX: [],
      ShowData: {},
      Res: {},
      stoDate: [],
      newMaterial: [], //存放物料号
      newBatch: [], //存放所有的批次号
      allNum: 0, //取出当前表格中所有物料的数量
      allNumTwo: 0,
      startDate: "", //开始日期
      endDate: "", //结束日期
      keyword: "", //搜索关键字
      newArry: [],
      item: "", //存放子项编号
      // 用于校验的数据
      noFitWuliao: [], //存放不符合数量标准的物料名称
      batchName: [],
      numOne: 0,
      numTwo: 0,
      stkstatus: "", //存放状态
    };
  },
  watch: {
    code(newValue) {
      if (this.orderNum) {
        if (newValue.length > 9) {
          let res = parseQRCode(newValue, this.orderMill);
          this.Res = JSON.parse(JSON.stringify(res));
          if (res) {
            if (!this.rowData.find((it) => it.palletNo == res.palletNo)) {
              if (res.prodDate == null || res.prodDate == "") {
                this.$toast("拍码生产日期为空");
                this.code = "";
                return;
              }
              if (this.newMaterial.indexOf(res.materialCode) == -1) {
                // 物料号校验
                toast("订单中不存在该物料");
                this.code = "";
                return;
              }
              //验证批次
              this.checkBachNo(res.materialCode, res.batchCod);
              if (this.batchName[0] != null) {
                this.$toast("物料批次不一致");
                this.batchName = [];
                this.code = "";
                return;
              }
              this.ShowData = JSON.parse(JSON.stringify(res));
              // 改变日期格式
              let SC = "20" + this.ShowData.prodDate;
              let YX = "20" + this.ShowData.BBD;
              this.ShowData.prodDate =
                SC.substring(0, 4) +
                "-" +
                SC.substring(4, 6) +
                "-" +
                SC.substring(6, 8);
              this.ShowData.BBD =
                YX.substring(0, 4) +
                "-" +
                YX.substring(4, 6) +
                "-" +
                YX.substring(6, 8);
              if (this.ShowData) {
                this.ShowStatue = true;
                this.rowData.push(res);
                this.stoDate.forEach((item) => {
                  if (res.materialCode == item.material) {
                    if (item.batchtrac == "X") {
                      if (
                        item.material == res.materialCode &&
                        item.batch == res.batchCod
                      ) {
                        item.aquantity =
                          (Number(item.aquantity) * 1000 +
                            res.quantity * 1000) /
                          1000;
                      }
                    } else {
                      if (item.material == res.materialCode) {
                        item.aquantity =
                          (Number(item.aquantity) * 1000 +
                            res.quantity * 1000) /
                          1000;
                      }
                    }
                  }
                });
              }
              res = "";
              this.code = "";
            } else {
              toast("拍码重复");
              this.code = "";
            }
          } else {
            toast("请检查信息是否完整");
            this.code = "";
          }
        } else {
          this.code = "";
        }
      } else {
        toast("请选择关联单号");
        this.code = "";
      }
    },
  },

  methods: {
    // 校验批次
    checkBachNo(wuliaohao, pici) {
      this.stoDate.forEach((item) => {
        if (item.material == wuliaohao) {
          if (item.batchtrac == "X") {
            if (this.newBatch.indexOf(pici) == -1) {
              this.batchName.push(item);
            }
          }
        }
      });
    },

    // 获取焦点时触发的方法
    focus() {
      // 获取焦点时阻止键盘弹出
      this.$refs.code.$refs.input.setAttribute("readonly", "readonly");
      setTimeout(() => {
        this.$refs.code.$refs.input.removeAttribute("readonly");
      }, 200);
    },
    get_date(val, startDate, endDate, keyword) {
      this.startDate = startDate; //获取开始日期
      this.endDate = endDate; //获取结束日期
      this.keyword = keyword; //获取搜索关键字
      this.stoDate = val;
      this.newMaterial = [];
      this.newBatch = [];
      // 调用该函数获取去重后的比较数据
      this.getNoRepeat();
    },
    getNoRepeat() {
      this.stoDate.forEach((val) => {
        this.newMaterial.push(val.material);
        if (val.batchtrac == "X") {
          this.newBatch.push(val.batch);
        }
      });
    },
    closetwo() {
      this.orderNumBerVisible = false;
      this.Fresh();
    },
    close() {
      this.$refs.code.focus();
      this.orderNumBerVisible = false;
      this.orderNum = this.$store.state.number;
      this.orderStorage = this.$store.state.storage;
      this.orderMill = this.$store.state.receivemill;
    },
    setTitle() {
      let res = this.titles.get(this.type);
      this.$store.commit("SET_NAVIGATION", res);
    },
    onRemoveSelected() {
      let selectedData = this.gridApi.getSelectedRows();
      if (this.rowData[0] == null) {
        this.$toast("当前表格为空");
      } else {
        if (selectedData[0] == null) {
          this.$toast("请选择要删除的数据");
        } else {
          this.stoDate.forEach((item) => {
            if (item.material == selectedData[0].materialCode) {
              if (item.batchtrac == "X") {
                if (
                  item.material == selectedData[0].materialCode &&
                  item.batch == selectedData[0].batchCod
                ) {
                  item.aquantity =
                    (Number(item.aquantity) * 1000 -
                      selectedData[0].quantity * 1000) /
                    1000;
                }
              } else {
                if (item.material == selectedData[0].materialCode) {
                  item.aquantity =
                    (Number(item.aquantity) * 1000 -
                      selectedData[0].quantity * 1000) /
                    1000;
                }
              }
            }
          });
          let selctIndex = this.gridApi.applyTransaction({
            remove: selectedData,
          });
          // 删除选中的数据
          this.rowData.splice(selctIndex.remove[0].childIndex, 1);
          this.otherData.splice(selctIndex.remove[0].childIndex, 1);
        }
      }
    },
    //传回来把组件关闭
    Suretwo(val) {
      setTimeout(() => {
        this.ShowStatue = false;
      }, 100);
      this.location = val;
      this.Res.StorehouseName = this.location;
      // 获取提交数据的子项编号
      this.item = ""; //清空上一次数据
      this.stkstatus = "";
      this.stoDate.forEach((item) => {
        if (item.batchtrac == "X") {
          if (
            item.material == this.ShowData.materialCode &&
            item.batch == this.ShowData.batchCod
          ) {
            this.item = item.item;
            this.stkstatus = item.stkstatus;
          }
        } else {
          if (item.material == this.ShowData.materialCode) {
            this.item = item.item;
            this.stkstatus = item.stkstatus;
          }
        }
      });
      this.getOther();
      setTimeout(() => {
        this.$refs.code.focus();
      }, 300);
    },
    //主列表数据
    getOther() {
      let SC = "20" + this.Res.prodDate;
      let SCdata =
        SC.substring(0, 4) +
        "-" +
        SC.substring(4, 6) +
        "-" +
        SC.substring(6, 8);
      let YX = "20" + this.Res.BBD;
      let YXdata =
        YX.substring(0, 4) +
        "-" +
        YX.substring(4, 6) +
        "-" +
        YX.substring(6, 8);
      this.otherData.push({
        make: this.Res.palletNo,
        gysdm: this.Res.commerialVendor,
        sl: this.Res.quantity,
        dw: this.Res.uom,
        ms: this.Res.batchCod,
        sc: SCdata,
        yx: YXdata,
        scs: this.Res.gsVendor,
        po: this.Res.poNo,
        bj: this.Res.inspectionNumber,
        gyspc: this.Res.vendorBatch,
        wlgg: this.Res.materialCfg,
        wl: this.Res.materialCode,
        kw: this.Res.StorehouseName,
        item: this.item,
        stkstatus: this.stkstatus,
      });
    },
    getOrderNum() {
      this.show = false;
      this.Fresh();
      this.orderNumBerVisible = true;
    },
    //看物料号是否重复
    Compare() {
      //将字符串划分为info数组
      this.info = this.code.match(/(?<=\)).+?(?=\()/g);
      let compare = this.info[8];
      this.rowData.map((item) => {
        if (compare == item.make) {
          this.$toast.fail("拍号重复");
          this.code = "";
          this.zt = false;
        } else {
          this.zt = true;
        }
      });
    },
    //小组件确认
    confirmButton(show, sure) {
      this.show = show;
      this.sure = sure;
      if (this.sure == true) {
        this.Send();
        this.Fresh();
        this.sure = false;
      }
    },
    //小组件取消
    cancelButton(show, sure) {
      this.show = show;
      this.sure = sure;
    },
    //获取当前的日期
    getNowDate() {
      let now = new Date();
      let year = now.getFullYear(); //年
      let month = now.getMonth() + 1; //月
      let day = now.getDate(); //日
      return `${year}-${month}-${day}`;
    },
    //向后台提交数据
    Send() {
      let type = "ProcurementInbound";
      let submit = {
        CreatedId: JSON.parse(localStorage.getItem("userid")),
        BillType: "ProcurementInbound",
        BillTypeName: "STO收货",
        CreatedName: JSON.parse(localStorage.getItem("username")),
        Plant: this.orderMill,
        InventoryStatus: "U",
        InDate: this.getNowDate(),
        LinkNo: this.orderNum,
      };
      PostSubmitA("/GenerateIMSXml.asmx/SaveForm", [
        submit,
        this.otherData,
        type,
      ])
        .then((res) => {
          toast(res.data.d.message);
          // console.log(res.data);
        })
        .catch((Error) => {
          toast(Error.data.message);
          // console.log(Error);
        });
    },
    async onSubmit() {
      this.addPrice();
      if (this.rowData.length == 0) {
        this.$toast("当前表格为空");
      } else {
        let res = await PostOrder("/api/IMSPDA/getStOrder", {
          sdate: this.startDate,
          edate: this.endDate,
          keys: this.keyword,
        });
        if (res.status == 200) {
          res.data.data.forEach((item) => {
            this.newArry.push(item.stno);
          });
          if (this.newArry.indexOf(this.orderNum) == -1) {
            this.$toast("改订单已关闭,无法提交");
          } else {
            this.stoDate.forEach((item) => {
              if (Number(item.aquantity) == Number(item.quantity)) {
                this.noFitWuliao.push(item);
              }
            });
            //总数验证
            this.rowData.forEach((item) => {
              this.numOne = (this.numOne * 1000 + item.quantity * 1000) / 1000;
            });
            this.stoDate.forEach((item) => {
              this.numTwo =
                (this.numTwo * 1000 + Number(item.quantity) * 1000) / 1000;
            });
            if (
              this.noFitWuliao.length == this.stoDate.length &&
              this.numOne == this.numTwo
            ) {
              this.$toast({
                type: "success",
                message: "提交成功",
              });
              this.Send();
              this.Fresh();
              this.newArry = [];
              this.noFitWuliao = [];
            } else {
              this.ifShowNoFit = true;
              this.noFitWuliao = [];
              this.allNumTwo = 0;
              this.allNum = 0;
              this.numOne = 0;
              this.numTwo = 0;
            }
          }
        } else {
          this.$toast("后台错误,无法提交");
        }
      }
    },
    //提交完成之后清空页面
    Fresh() {
      this.numOne = 0;
      this.numTwo = 0;
      this.$store.state.ph = "";
      this.$store.state.wl = "";
      this.$store.state.sl = "";
      this.orderNum = "";
      this.orderStorage = "";
      this.orderMill = "";
      this.code = "";
      this.rowData = [];
      this.otherData = [];
      this.allNumTwo = 0;
      this.allNum = 0;
    },
    //如果表格里面有多余的空挡，删除
    ClearTab(data) {
      data.map((item, index) => {
        if (item.make == "" || item.make == undefined) {
          data.splice(index, 1);
        }
      });
    },
    addPrice() {
      let copymodel = [];
      let Model = [];
      for (var i in this.rowData) {
        copymodel.push(this.rowData[i].model);
      }
      for (var j in copymodel) {
        if (Model.indexOf(copymodel[j]) == -1) {
          Model.push(copymodel[j]);
        }
      } //得到了所有的model种类
      //将Model以属性的方式放入对象数组DX,
      //并且给对象数组DX添加price属性
      let DX = [];
      Model.map((item) => {
        DX.push({
          model: item,
        });
      });
      DX.forEach((itm) => {
        itm.price = 0;
      });
      //遍历rowdata中的所有model将所有的price累加赋值给DX.price
      for (var k in DX) {
        for (var m in this.rowData) {
          if (this.rowData[m].model == DX[k].model) {
            DX[k].price += parseInt(this.rowData[m].price);
          }
        }
      }
      this.DX = DX;
      // console.log(this.DX);
    },

    // 修改数量确认按钮
    SureUpdate() {
      if (this.needUpdateNum == "") {
        this.$toast("未输入数量无法修改");
      } else {
        this.selectDate[0].quantity = this.needUpdateNum;
        this.gridApi.applyTransaction({ update: this.selectDate });
        this.otherData.forEach((item) => {
          if (this.selectDate[0].palletNo == item.make) {
            item.sl = Number(this.needUpdateNum);
          }
        });
        this.needUpdateNum = "";
      }
    },
    // 关闭enter键
    closeEnter() {
      document.onkeydown = function (e) {
        //捕捉回车事件
        var ev = typeof event != "undefined" ? window.event : e;
        if (ev.keyCode == 13 || event.which == 13) {
          return false;
        }
      };
    },
  },
  mounted() {
    this.type = parseInt(this.$route.params.type);
    this.setTitle();
    this.closeEnter();
  },
};
</script>

<style lang="less" scoped>
.ag-theme-alpine .ag-root-wrapper {
  border-left-width: 0;
  border-right-width: 0;
}
.tip {
  text-align: center;
  margin-bottom: 1rem;
  padding: 1rem;
  height: 1rem;
}
</style>
